import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


public class CheckAndStartProgram {

    // 检查程序是否正在运行
    public static boolean isProgramRunning(String programName) {
        try {
            Process process = Runtime.getRuntime().exec("ps -ef | grep " + programName + " | grep -v grep");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(programName)) {
                    return true;
                }
            }
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 执行指定命令
    public static void executeCommand(String command) {
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        int interval = 60 * 1000; // 检查间隔，单位为毫秒，这里设置为 1 分钟

        // 定义多个任务
        List<Task> tasks = new ArrayList<>();
        tasks.add(new Task("your_program_name_1", "your_start_command_1"));
        tasks.add(new Task("your_program_name_2", "your_start_command_2"));
        // 可以继续添加更多任务

        while (true) {
            for (Task task : tasks) {
                if (!isProgramRunning(task.programName)) {
                    System.out.println(task.programName + " 未运行，正在启动...");
                    executeCommand(task.startCommand);
                } else {
                    System.out.println(task.programName + " 正在运行。");
                }
            }

            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}    